package com.lzh.shijicloudstack.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.shijicloudstack.mapper.CalendarRecordMapper;
import com.lzh.shijicloudstack.model.dto.calendarRecord.AddEventDto;
import com.lzh.shijicloudstack.model.dto.calendarRecord.DateRangeDto;
import com.lzh.shijicloudstack.model.dto.calendarRecord.EditEventDto;
import com.lzh.shijicloudstack.model.entity.CalendarRecord;
import com.lzh.shijicloudstack.model.vo.calendarRecord.CalendarRecordVO;
import com.lzh.shijicloudstack.service.CalendarRecordService;
import com.lzh.shijicloudstack.utils.DateUtil;
import com.lzh.shijicloudstack.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 菜谱分类服务实现类
 *
 * @author luzhiheng
 * @date 2025-04-17
 */
@Service
public class CalendarRecordServiceImpl extends ServiceImpl<CalendarRecordMapper, CalendarRecord> implements CalendarRecordService {

    @Override
    public List<CalendarRecordVO> findCookbookByRangeDate(DateRangeDto dto) {
        List<CalendarRecordVO> calendarRecordList = baseMapper.selectByDateRange(SecurityUtils.getUserId(), dto.getBeginDate(), dto.getEndDate());
        return calendarRecordList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addEvent(AddEventDto dto) {
        List<Long> cookbookIdList = dto.getCookbookIdList();
        String date = dto.getDatetime();
        String remark = dto.getRemark();

        for (Long cookbookId : cookbookIdList) {
            CalendarRecord calendarRecord = new CalendarRecord();
            calendarRecord.setCookbookId(cookbookId);
            calendarRecord.setDate(new DateUtil().parseDatetime(date));
            calendarRecord.setRemark(remark);
            calendarRecord.setEatType(dto.getEatType());
            calendarRecord.setCreateTime(new Date());
            calendarRecord.setCreateName(SecurityUtils.getUserId() + "");
            calendarRecord.setCreateUserId(SecurityUtils.getUserId() + "");
            calendarRecord.setOpenFlag(1);
            baseMapper.insert(calendarRecord);
        }

        return true;
    }

    @Override
    public Boolean editEvent(EditEventDto dto) {
        CalendarRecord calendarRecord = baseMapper.selectById(dto.getId());
        if (calendarRecord == null) {
            return false;
        }
        calendarRecord.setEatType(dto.getEatType());
        calendarRecord.setDate(new DateUtil().parseDatetime(dto.getDatetime()));
        calendarRecord.setCookbookId(dto.getCookbookId());
        baseMapper.updateById(calendarRecord);
        return true;
    }

}
